//
//  NetWorkTools.swift
//  
//
//  Created by 李振兴 on 15/10/16.
//
//

import UIKit
import AFNetworking
enum HMRequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}
class NetWorkTools: AFHTTPSessionManager {
    // MARK: - 应用程序信息
    //private let appKey = "3863118655"
    //private let appSecret = "b94c088ad2cdae8c3b9641852359d28c"
    //private let redirectUrl = "http://www.baidu.com/"

    private let appKey = "1042257240"
    private let appSecret = "a95e396e35032573cf7054a609e946f1"
    private let redirectUrl = "http://www.huanqiu.com/"
    typealias HMRequestCallBack =  (result:AnyObject?,error:NSError?)->()
   
    // 单例
    static let sharedTools: NetWorkTools = {
        
        let tools = NetWorkTools(baseURL: nil)
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
     }()
    
    
}
// MARK: - 发表微博
extension NetWorkTools{
    /// 发布微博
    ///
    /// - parameter status:   微博文本
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/update](http://open.weibo.com/wiki/2/statuses/update)
    func sendStatus(status: String, image:UIImage?, finished: HMRequestCallBack) {
        
        // 1. 创建参数字典
        var params = [String:AnyObject]()
        
        // 2. 设置参数
        params["status"] = status
        
        // 3. 判断是否上传图片
        if image == nil {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
        } else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let data = UIImagePNGRepresentation(image!)
            
            upload(urlString, data: data!, name: "pic", parameters: params, finished: finished)
        }

    }

}
// MARK: - 微博数据相关方法
extension NetWorkTools {
    
    /// 加载微博数据
    ///
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(since_id since_id: Int, max_id: Int,finished: HMRequestCallBack) {
        
        // 1. 创建参数字典
        var params = [String:AnyObject]()
        
        if since_id > 0 {
            params["since_id"] = since_id
        }else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        // 2. 准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 3. 发起网络请求
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

//MARK:用户相关方法
extension NetWorkTools{
    
    func loadUserInfo(uid: String, finished: HMRequestCallBack){
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 1. 创建参数字典
        var params = [String:AnyObject]()
        
        params["uid"] = uid

        tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
    }
    
}
// MARK: - OAuth 相关方法
extension NetWorkTools{
    var oAuthURL:NSURL {
        //https://api.weibo.com/oauth2/authorize?client_id=1042257240&redirect_uri=http://www.baidu.com/
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    
    //MARK:获取AccessToken
    func loadAccessToken(code:String,finished:HMRequestCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        request(.POST, URLString: urlString, parameters: params, finished: finished)
    }
    
  
}
//MARK:封装AFN
extension NetWorkTools{
    /**
    参数追加token
    
    - parameter parameters: 参数字典
    
    - returns: 返回是否追加成功
    */
    private func appendToken(inout parameters: [String: AnyObject]?)->Bool{
        guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
            // token 无效
            return false
        }
        if parameters == nil{
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token
        return true
    }

    /**
    - parameter method:     使用Token进行封装
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调    */
    func tokenRequest(method:HMRequestMethod, URLString: String, var parameters:[String: AnyObject]? , finished:HMRequestCallBack){
        // 1.追加token
        if !appendToken(&parameters) {
            // token 无效
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        
        request(method, URLString: URLString, parameters: parameters, finished: finished)
    }
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    func request(method:HMRequestMethod, URLString: String, parameters:[String: AnyObject]? , finished:HMRequestCallBack){
        
        let success = {(task:NSURLSessionDataTask, result:AnyObject)->() in
            finished(result: result,error: nil)
        }
        let failure = {(result:NSURLSessionDataTask, error:NSError)->() in
            print("error=\(error)")
            finished(result: result,error: nil)
        }
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }else if method == HMRequestMethod.POST {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
        
    }
    
    /// 上传文件
    private func upload(URLString: String, data: NSData, name: String, var parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        
        // 1.追加token
        if !appendToken(&parameters) {
            // token 无效
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        /**
        1. data 要上传文件的二进制数据
        2. name 是服务器定义的字段名称 － 后台接口文档会提示
        3. fileName 是保存在服务器的文件名，但是：现在通常可以`乱写`，后台会做后续的处理
        - 根据上传的文件，生成 缩略图，中等图，高清图
        - 保存在不同路径，并且自动生成文件名
        
        - fileName 是 HTTP 协议定义的属性
        4. mimeType / contentType: 客户端告诉服务器，二进制数据的准确类型
        - 大类型/小类型
        * image/jpg image/gif image/png
        * text/plain text/html
        * application/json
        - 无需记忆
        - 如果不想告诉服务器准确的类型
        * application/octet-stream
        */
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            }, success: { (_, result) -> Void in
                finished(result: result, error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }


}